package org.tang.gateway.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Tang
 * @classname RibbonWatchConfigure
 * @description [  ]
 * @date 2022/9/26 17:00
 */
@ConditionalOnProperty(prefix = "ribbon",value = "watch-enable",havingValue = "true")
@EnableConfigurationProperties(value = {RibbonWatchClients.class})
@Configuration
public class RibbonWatchConfigure {

    /**
     * 配置类
     * @return
     */
    @Bean
    public RibbonWatchClients ribbonWatchClients() {
        return new RibbonWatchClients();
    }

    /**
     *  ribbon client 主动初始化器
     * @param springClientFactory
     * @param routeDefinitionLocator
     * @return
     */
    @Bean
    public RibbonApplicationContextInitializer ribbonApplicationContextInitializer(SpringClientFactory springClientFactory,
                                                                                   RouteDefinitionLocator routeDefinitionLocator) {
        return new RibbonApplicationContextInitializer(springClientFactory,routeDefinitionLocator,ribbonWatchClients());
    }

    /**
     * 事件订阅者
     * @param routeDefinitionLocator
     * @return
     */
    @Bean
    public InstancesChangeSubscriber instancesChangeSubscriber(RouteDefinitionLocator routeDefinitionLocator) {
        return new InstancesChangeSubscriber(routeDefinitionLocator,ribbonWatchClients());
    }

}
